const CFG = require('../config');
const mqtt = require('mqtt');
const timLib =require('../comm/time-lib');
const FUN = require('../comm/func');

//开启一个订阅对象
function newClient(clientId, callback)
{
  let mqttConfig = CFG.MqttClient;
  mqttConfig.clientId = clientId;

  let Client = mqtt.connect(mqttConfig);//连接到服务端

  // 连接成功
  Client.on('connect', (Packet)=>{
    console.log(timLib.NowStr(), 'Mqtt connect sucess!', clientId, Client.connected);
    if (Client.connected) {
      setTimeout(()=>{
        callback(Client);
      },1000);
    }
  })

  Client.on('error', (error)=>{
    console.log(timLib.NowStr(), 'Mqtt error', clientId, error.errno);
  })

  Client.on('close', ()=>{
    // console.log(timLib.NowStr(), 'Mqtt close!', clientId, Client.connected);
    Client.end();
    setTimeout(()=>{
      newClient(clientId, callback);
    },10000); // 延时一段时间再重连
    // global.shareEvt.emit('mqtt_close', clientId, callback);//为了让不同应用订阅不同主题
  })

  //收到消息
  Client.on('message',function(Topic,Payload,Packet){
    let Name=Topic.split('/');
    let Path=[];

    //解析路径信息
    if(Name.length==2)
    {
      Path.devType=Name[0];
      Path.func=Name[1];
    }
    else if(Name.length==3)
    {
      Path.devType=Name[0];
      Path.func=Name[1];
      Path.devId=Name[2];
    }
    else if(Name.length==4)
    {
      Path.project=Name[0];
      Path.devType=Name[1];
      Path.func=Name[2];
      Path.devId=Name[3];
    }
    else
    {
      console.log(timLib.NowStr(), 'Topic string fat error!');
      return;//topic格式不对
    }

    //轮询应用程序的回调
    this.msgHdrs.forEach((item)=>{
      item.mqMsgIn(Path,Payload,Packet);
    })

    //client.end();// close client
  })

  return Client;
}//end newMqttClient

// 单实例连接，一个应用只有一个
function singleClient(clientId)
{
  if (global.singleMqttClient) return;

  let mqttConfig = CFG.MqttClient;
  mqttConfig.clientId = clientId;

  let Client = mqtt.connect(mqttConfig);//连接到服务端

  // 连接成功
  Client.on('connect', (Packet)=>{
    console.log(timLib.NowStr(), 'Mqtt single connect sucess!', clientId);
    global.singleMqttClient = Client;
  })

  // 连接关闭时
  Client.on('close', ()=>{
    console.log(timLib.NowStr(), 'Mqtt single connect close!', clientId);
    delete global.singleMqttClient;
  })
}

// 单一连接发包
function singleClientPub(topic, msg)
{
  if (global.singleMqttClient) {
    global.singleMqttClient.publish(topic, msg);
  }
}

exports.newClient = newClient;
exports.singleClient = singleClient;
exports.singleClientPub = singleClientPub;